/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package diepafi;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import model.Song;
import programm.SeartchSong;

/**
 *
 * @author Παναγιώτης
 */
public class SongToPlaylistGUI extends javax.swing.JDialog {
    DefaultTableModel model;
    String[] selection=new String[3];
   
    /**
     * A return status code - returned if Cancel button has been pressed
     */
    public static final int RET_CANCEL = 0;
    /**
     * A return status code - returned if OK button has been pressed
     */
    public static final int RET_OK = 1;

    /**
     * Creates new form SongToPlaylistGUI
     * @param parent
     * @param modal
     */
    public SongToPlaylistGUI(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);

        initComponents();
        //γεμίζει τον πίνακα με όλα τα τραγούδια
        model=(DefaultTableModel) jTableSong.getModel(); 
        String seartch="";
        SeartchSong songIndex=new SeartchSong(seartch); //κλάση στο πακέτο programm
        List<Song> findSongs = new ArrayList();
        findSongs=songIndex.seartchIndexOf();
        int rowCount = jTableSong.getRowCount();
        for(int i=0;i<rowCount;i++) model.removeRow(0); //αδειάζει τον πίνακα για να "υποδεχθεί" τα νέα στοιχεία
        if(findSongs.size()<1) {
           JOptionPane.showMessageDialog(this , "Δεν υπάρχουν τραγούδια", "Περιεχόμενο", JOptionPane.ERROR_MESSAGE); //εμφανίζει μήνυμα αν δεν υπάρχει κανένα τραγούδι στη βάση
        } else {
            String singerName= new String(); //αποθηκεύει το όνομα καλλιτέχνη / συγκροτήματος, ανάλογα με το τραγούδι
            for(Song s: findSongs) {
                try {
                    singerName= s.getAlbumId().getGroupId().getGroupName();
                } catch(NullPointerException n) {
                    singerName= s.getAlbumId().getArtistId().getArtisticName();
                }
 
                model.addRow(new Object[] {s.getSongTitle(), singerName, s.getDuration()}); 
            }
        } 
        // Close the dialog when Esc is pressed
        String cancelName = "cancel";
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
        ActionMap actionMap = getRootPane().getActionMap();
        actionMap.put(cancelName, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                doClose(RET_CANCEL);
            }
        });
    }

    /**
     * @return the return status of this dialog - one of RET_OK or RET_CANCEL
     */
    public int getReturnStatus() {
        return returnStatus;
    }
    
    // Επιστρέφει το στοιχείο που επιλέξαμε
    public String[] getSelection() {
        return selection;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableSong = new javax.swing.JTable();
        jTextFieldSeartch = new javax.swing.JTextField();
        jButtonSeartch = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setTitle("Αναζήτηση τραγουδιών");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jPanel1.setForeground(new java.awt.Color(240, 240, 240));

        okButton.setBackground(new java.awt.Color(0, 0, 0));
        okButton.setForeground(new java.awt.Color(240, 240, 240));
        okButton.setText("Εισαγωγή");
        okButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        okButton.setNextFocusableComponent(cancelButton);
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setBackground(new java.awt.Color(0, 0, 0));
        cancelButton.setForeground(new java.awt.Color(240, 240, 240));
        cancelButton.setText("Άκυρο");
        cancelButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        cancelButton.setNextFocusableComponent(jButtonSeartch);
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jTableSong.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Τίτλος", "Καλλιτέχνης/Συγκρότημα", "Διάρκεια"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableSong.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTableSong);
        if (jTableSong.getColumnModel().getColumnCount() > 0) {
            jTableSong.getColumnModel().getColumn(0).setResizable(false);
        }

        jButtonSeartch.setBackground(new java.awt.Color(0, 0, 0));
        jButtonSeartch.setForeground(new java.awt.Color(240, 240, 240));
        jButtonSeartch.setText("Αναζήτηση");
        jButtonSeartch.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButtonSeartch.setNextFocusableComponent(okButton);
        jButtonSeartch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSeartchActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 2, 10)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 102, 0));
        jLabel1.setText("Η αναζήτηση περιλαμβάνει και το ονοματεπώνυμο του καλλιτέχνη, το οποίο δεν παρουσιάζεται στον πίνακα");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jTextFieldSeartch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonSeartch))
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldSeartch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonSeartch))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addGap(37, 37, 37))
        );

        getRootPane().setDefaultButton(okButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 461, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        model=(DefaultTableModel) jTableSong.getModel();
        int selectedRow=jTableSong.getSelectedRow();
      //αν πατήσουμε "Εισαγωγή", περνάει τα στοιχεία της επιλεγμένης σειράς σε έναν πίνακα String
        if(selectedRow!=-1) {
            selection[0]=model.getValueAt(selectedRow, 0).toString();
            selection[1]=model.getValueAt(selectedRow, 1).toString();
            selection[2]=model.getValueAt(selectedRow, 2).toString();
       }
        doClose(RET_OK);
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * Closes the dialog
     */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

    private void jButtonSeartchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSeartchActionPerformed
        model=(DefaultTableModel) jTableSong.getModel(); 
        String seartch=jTextFieldSeartch.getText(); //αντλεί το κείμενο από το textField αναζήτησης
        SeartchSong songIndex=new SeartchSong(seartch); //δημιουργεί ένα αντικείμενο SeartchSong (πακέτο programm) για να καλέσει την μέθοδο αναζήτησης
        List<Song> findSongs = new ArrayList(); 
        findSongs=songIndex.seartchIndexOf(); //περνάει τα αποτελέσματα της αναζήτησης σε μια λίστα
        int rowCount = jTableSong.getRowCount();
        for(int i=0;i<rowCount;i++) model.removeRow(0); //αδειάζει το table για να εισαχθούν τα αποτελέσματα
        if(findSongs.size()<1) { //ελέγχει αν δεν βρέθηκε κανένα τραγούδι
           JOptionPane.showMessageDialog(this , "Δεν βρέθηκαν τραγούδια με το επιλεγμένο κριτήριο", "Αναζήτηση", JOptionPane.ERROR_MESSAGE);
        } else {
            String singerName= new String(); //αποθηκεύει το όνομα καλλιτέχνη / συγκροτήματος, ανάλογα με το τραγούδι
            for(Song s: findSongs) {
                try {
                    singerName= s.getAlbumId().getGroupId().getGroupName();
                } catch(NullPointerException n) {
                    singerName= s.getAlbumId().getArtistId().getArtisticName();
                }
 
                model.addRow(new Object[] {s.getSongTitle(), singerName, s.getDuration()}); 
            }
        }    
    }//GEN-LAST:event_jButtonSeartchActionPerformed
    
    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SongToPlaylistGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SongToPlaylistGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SongToPlaylistGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SongToPlaylistGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(() -> {
            SongToPlaylistGUI dialog = new SongToPlaylistGUI(new javax.swing.JDialog(), true);
            dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });
            dialog.setVisible(true);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton jButtonSeartch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableSong;
    private javax.swing.JTextField jTextFieldSeartch;
    private javax.swing.JButton okButton;
    // End of variables declaration//GEN-END:variables

    private int returnStatus = RET_CANCEL;
}
